package com.mrd.gtimp.business.service;

import com.mrd.base.BaseBiz;
import com.mrd.gtimp.business.entity.Notification;
import com.mrd.gtimp.business.repository.NotificationDao;
import com.mrd.spring.repository.BaseRepository;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

/**
 * Created by dengdc on 2017/1/16.
 */
@Service
public class NotificationBiz extends BaseBiz<Notification> {
	@Resource
	private NotificationDao				notificationDao;
	/**
	 * 查询开关，默认关闭，需要通过其他方式打开
	 */
	private static boolean				querySwitch		= false;
	/**
	 * 页面查询到的通知都是从本集合中得到
	 */
	private static List<Notification>	notifications	= new ArrayList<>();

	/**
	 * 打开查询，使用环境例如：在前台插入了新的通知后，需要打开查询开关；然后在查询之后马上关掉
	 */
	public void openQuery() {
		querySwitch = true;
	}

	@Override
	@Resource
	@Qualifier("notificationDao")
	public void setBaseRepository(BaseRepository<Notification, String> baseRepository) {
		this.baseRepository = baseRepository;
	}

	/**
	 * 查询后关掉查询开关或者手动关闭
	 */
	public void closeQuery() {
		querySwitch = false;
	}

	/**
	 * 查找有效的通知
	 */
	public List<Notification> findEffectiveNotification() {
		if(querySwitch) {
			List<Notification> list = notificationDao
			        .findByStateOrderByBeginTimeAsc(Notification.stateEnum.effective.value());
			List<Notification> expiredNotis = new ArrayList<>();
			for(Notification notification : list) {
				if(notification.getEndTime().before(new Date())) {
					expiredNotis.add(notification);
				}
			}
			setExpiredNotificationsState(expiredNotis);
			list.removeAll(expiredNotis);
			notifications = list;
			closeQuery();
		}
		return notifications;
	}

	/**
	 * 找到应该被看到的通知，使用传过来的已读ID进行排除
	 * @param readedIds
	 *            已读ID
	 */
	public List<Notification> findShouldReadNotification(String... readedIds) {
		List<Notification> effectiveNotis = findEffectiveNotification();
		List<Notification> shouldReadNotis = new ArrayList<>();
		if(ArrayUtils.isEmpty(readedIds)) {
			shouldReadNotis.addAll(effectiveNotis);
		}
		for(Notification effectiveNoti : effectiveNotis) {
			for(String readedId : readedIds) {
				if(readedId.equals(effectiveNoti.getId())) {
					continue;
				}
				if(effectiveNoti.getEndTime().before(new Date())) {
					continue;
				}
				shouldReadNotis.add(effectiveNoti);
			}
		}
		return shouldReadNotis;
	}

	/**
	 * 设置已过期的通知的状态为结束
	 * @param expiredNotis
	 */
	@Transactional
	public void setExpiredNotificationsState(List<Notification> expiredNotis) {
		if(CollectionUtils.isEmpty(expiredNotis)) {
			return;
		}
		for(Notification expiredNoti : expiredNotis) {
			expiredNoti.setState(Notification.stateEnum.finished.value());
		}
		notificationDao.save(expiredNotis);
	}
}
